package com.example.barrage.service;

import com.example.barrage.handler.BarrageHandler;
import com.example.barrage.model.BarrageMessage;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@RocketMQMessageListener(topic = "barrage-topic", consumerGroup = "barrage-consumer-group")
public class BarrageConsumerService implements RocketMQListener<String> {

    private static final Logger logger = LoggerFactory.getLogger(BarrageConsumerService.class);

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private BarrageHandler barrageHandler;

    @Override
    public void onMessage(String message) {
        try {
            logger.info("收到来自RocketMQ的原始消息: {}", message);
            BarrageMessage barrageMessage = objectMapper.readValue(message, BarrageMessage.class);
            logger.info("解析来自RocketMQ的弹幕消息 - 用户ID: {}, 用户名: {}, 内容: {}", 
                barrageMessage.getUserId(), barrageMessage.getUsername(), barrageMessage.getContent());
            
            // 通过WebSocket广播消息给所有在线用户
            barrageHandler.broadcastMessage(barrageMessage);
            
            logger.info("已将来自RocketMQ的弹幕消息广播给所有连接的客户端");
        } catch (Exception e) {
            logger.error("处理来自RocketMQ的弹幕消息失败: {}", message, e);
        }
    }
}